#检查链接是否有效,如果失效则更新数据库，如果有效则不更新数据库，is_lost字段表示链接是否失效，正常为False，失效为True。
import requests
from django.core.management.base import BaseCommand
from django.conf import settings
from ctbloge.apps.blog.models import FriendLink
import logging
class Command(BaseCommand):
    help = '检查友情链接是否有效'

    def handle(self, *args, **options):
        for link in FriendLink.objects.all():
            try:
                response = requests.get(link.url, timeout=5)
                if response.status_code == 200:
                    link.is_lost = False#链接有效
                    link.save()
                    logging.info(f'{link.name} 链接有效')
                else:
                    link.is_lost = True#链接失效
                    link.save()
                    logging.info(f'{link.name} 链接失效')
            except requests.exceptions.RequestException:
                link.is_lost = True
                link.save()
                logging.info(f'{link.name} 链接失效')